//
//  ChinesToPinYin.m
//  Cunli
//
//  Created by 湛亚 on 15/6/30.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "ChinesToPinYin.h"

@implementation ChinesToPinYin


//----------------------------------------------------------------
Boolean CFStringTransform(CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse);
//参数1：待转换字符串：Mutable类型
//参数2：转换的范围
//参数3：转换的选项
//kCFStringTransformMandarinLatin         拼音带声调标记
//kCFStringTransformStripCombiningMarks   声调字符转换成普通字符
//参数4：是否逆向转换
//返回值：转换成功 YES 转换失败 NO
//----------------------------------------------------------------

//转换为拼音（小写）
+ (NSString*)chineseToPinYin:(NSString*)chinese
{
    //chinese字符串不能为空和nil
    if ([chinese isEqualToString:@""]||(chinese == nil))
    {
        return @"";
    }
    
    NSMutableString *pinyin = [chinese mutableCopy];
    
    
    //1 转换成拼音（带声调）
    CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformMandarinLatin, NO);
    //2 去声调
    CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformStripCombiningMarks, NO);
    
    
    //3 去除转换后的字符串中的空格
    NSRange range = [pinyin rangeOfString:@" "];
    while (range.location != NSNotFound)
    {
        [pinyin deleteCharactersInRange:range];
        range = [pinyin rangeOfString:@" "];
    }
    
    //4 全部转换成小写
    NSString *string = [pinyin lowercaseString];
    
    return string;
}
//获取首字符（大写）
+ (NSString*)chineseToPinYinHead:(NSString*)chinese
{
    //chinese字符串不能为空和nil
    if ([chinese isEqualToString:@""]||(chinese == nil))
    {
        return @"";
    }
    
    NSMutableString *pinyin = [chinese mutableCopy];
    
    
    //1 转换成拼音（带声调）
    CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformMandarinLatin, NO);
    //2 去声调
    CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformStripCombiningMarks, NO);
    
    
    //3 获取第一个字符
    NSString *pinYinHea = [pinyin substringToIndex:1];
    
    //4 转换成大写
    NSString *string = [pinYinHea uppercaseString];
    
    return string;
}
//判断字符串是否包含汉字
+ (BOOL)isIncludeChineseInString:(NSString *)string
{
    for (int i = 0; i < string.length; i ++)
    {
        unichar ch = [string characterAtIndex:i];
        if (0x4e00 < ch  && ch < 0x9fff)
        {
            return true;
        }
    }
    return false;
}

//判断字符串首字符是否为汉字
+ (BOOL)isChineseInStringOfFirst:(NSString *)string
{
    //string字符串不能为空
    if ([string isEqualToString:@""])
    {
        return false;
    }
    
    unichar ch = [string characterAtIndex:0];
    
    if (0x4e00 < ch  && ch < 0x9fff)
    {
        return true;
    }
    
    return false;
}

@end
